package sys;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtil {
	public static String read(Class<?> clazz, String file) {
		try {
			return readFully(clazz.getResourceAsStream(file));
		} catch(Exception exc) {
			throw new RuntimeException("Failure reading file " + file, exc);
		}
	}
	
    public static java.net.URL getResource(Class<?> clazz, String file) {
    	return clazz.getResource(file);      
    }
    
	private static String readFully(InputStream is) {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			StringBuilder s = new StringBuilder();
			String l;
			while((l = reader.readLine()) != null){
				s.append(l).append('\n');
			}
			
			return s.toString();
		} catch(Exception exc) {
			throw new RuntimeException("Failure reading input stream", exc);
		}
	}

	public static InputStream createInputStream(Class<?> clazz, String fileName) {
		InputStream inputStream = getStreamByClass(clazz, fileName);
		if (inputStream == null) {
			inputStream = getStreamByClassLoader(fileName);
		}

		if (inputStream == null) {
			throw new IllegalArgumentException("Can't locate the file: " + fileName);
		}
		return inputStream;
	}

	public static InputStream createInputStream(String fileName) {
		InputStream inputStream = getStreamByClassLoader(fileName);

		if (inputStream == null) {
			throw new IllegalArgumentException("Can't locate the file: " + fileName);
		}
		return inputStream;
	}
    
	private static InputStream getStreamByClass(Class<?> clazz, String fileName) {
		InputStream inputStream = null;
		
		if (clazz == null) {
			return null;
		}

		try {
			inputStream = clazz.getResourceAsStream(fileName);
		} catch (Exception e) {
			// TODO Be silent with this exception, writer to log file
		}
		return inputStream;
	}
	
	private static InputStream  getStreamByClassLoader(String fileName){
		InputStream inputStream = null;
		try {
			inputStream = createInputStream(Thread.currentThread().getContextClassLoader(), fileName);
		} catch (Exception e) {
			// TODO Be silent with this exception, writer to log file
		}

		if (inputStream != null){
			return inputStream;
		}
		
		try {
			inputStream = createInputStream(FileUtil.class.getClassLoader(), fileName);
		} catch (Exception ex) {
			//todo
		}

		if (inputStream == null){
			throw new IllegalArgumentException("Can't locate the file: " + fileName);
		}

		return inputStream;
	}

	private static InputStream createInputStream(ClassLoader classLoader, String fileName) throws Exception {
		return classLoader.getResourceAsStream(SystemUtil.fileSeparator + fileName);
	}
}
